"""
用户管理路由模块

提供用户登录、文件管理、统计等功能
"""

from fastapi import APIRouter, HTTPException, Header, UploadFile, File
from fastapi.responses import FileResponse
from typing import Optional
import os
import uuid
import httpx
from pathlib import Path
import json
from datetime import datetime, timedelta

from utils.file_manager import FileManager
from config import STORAGE_CONFIG
from dotenv import load_dotenv
import os
load_dotenv()

router = APIRouter(prefix="/api/user", tags=["用户管理"])
file_manager = FileManager()

# 微信小程序配置
WECHAT_CONFIG = {
    "appid": os.getenv("APP_ID"),
    "secret": os.getenv("APP_SECRET")
}

@router.post("/login", response_model=dict)
async def wechat_login(request_data: dict):
    """
    微信登录接口
    
    Args:
        code: 包含微信登录code的字典
        
    Returns:
        {
            "success": true,
            "message": "登录成功",
            "data": {
                "openid": "用户openid",
                "token": "访问令牌"
            }
        }
    """
    try:
        # 向微信服务器请求openid
        wechat_url = f"https://api.weixin.qq.com/sns/jscode2session"
        params = {
            "appid": WECHAT_CONFIG["appid"],
            "secret": WECHAT_CONFIG["secret"],
            "js_code": request_data["code"],
            "grant_type": "authorization_code"
        }
        
        async with httpx.AsyncClient() as client:
            response = await client.get(wechat_url, params=params)
            result = response.json()
            
        if "openid" not in result:
            raise HTTPException(
                status_code=400, 
                detail=result.get("errmsg", "获取openid失败")
            )
            
        openid = result["openid"]
        
        # 创建用户目录
        user_temp_dir = Path("temp") / openid
        user_temp_dir.mkdir(parents=True, exist_ok=True)
        
        # 生成简单token（实际项目中应使用JWT）
        token = str(uuid.uuid4())
        
        return {
            "success": True,
            "message": "登录成功",
            "data": {
                "openid": openid,
                "token": token
            }
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/stats", response_model=dict)
async def get_user_stats(openid: str = Header(...)):
    """
    获取用户统计信息
    
    Args:
        openid: 用户openid（从header获取）
        
    Returns:
        {
            "success": true,
            "data": {
                "stats": {
                    "totalPhotos": 总照片数,
                    "thisMonth": 本月照片数
                },
                "storage": {
                    "totalFiles": 总文件数,
                    "totalSize": 总大小,
                    "standardCount": 标准照数量,
                    "hdCount": 高清照数量
                }
            }
        }
    """
    try:
        if not openid:
            raise HTTPException(status_code=401, detail="未登录")
            
        # 获取用户目录
        user_dir = Path(STORAGE_CONFIG["base_dir"]) / openid
        if not user_dir.exists():
            return {
                "success": True,
                "data": {
                    "stats": {
                        "totalPhotos": 0,
                        "thisMonth": 0
                    },
                    "storage": {
                        "totalFiles": 0,
                        "totalSize": "0 KB",
                        "standardCount": 0,
                        "hdCount": 0
                    }
                }
            }
            
        # 统计文件
        stats = file_manager.get_user_stats(str(user_dir))
        
        return {
            "success": True,
            "data": stats
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/files", response_model=dict)
async def get_user_files(
    file_type: Optional[str] = None,
    limit: int = 50,
    offset: int = 0,
    openid: str = Header(...)
):
    """
    获取用户文件列表
    
    Args:
        file_type: 文件类型过滤
        limit: 返回数量限制
        offset: 偏移量
        openid: 用户openid
        
    Returns:
        {
            "success": true,
            "files": [
                {
                    "path": 文件路径,
                    "url": 访问URL,
                    "filename": 文件名,
                    "size": 文件大小,
                    "created_at": 创建时间,
                    "file_type": 文件类型,
                    "size_name": 尺寸名称,
                    "background_color": 背景颜色
                }
            ],
            "total": 总数
        }
    """
    try:
        if not openid:
            raise HTTPException(status_code=401, detail="未登录")
            
        user_dir = Path(STORAGE_CONFIG["base_dir"]) / openid
        if not user_dir.exists():
            return {"success": True, "files": [], "total": 0}
            
        files = file_manager.list_user_files(
            str(user_dir), 
            file_type, 
            limit, 
            offset
        )
        
        return {
            "success": True,
            "files": files,
            "total": len(files)
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/files/{file_path:path}", response_model=dict)
async def delete_user_file(
    file_path: str,
    openid: str = Header(...)
):
    """
    删除用户文件
    
    Args:
        file_path: 文件路径
        openid: 用户openid
        
    Returns:
        {"success": true, "message": "删除成功"}
    """
    try:
        if not openid:
            raise HTTPException(status_code=401, detail="未登录")
            
        # 验证文件路径属于该用户
        user_dir = Path(STORAGE_CONFIG["base_dir"]) / openid
        full_path = user_dir / file_path
        
        if not str(full_path).startswith(str(user_dir)):
            raise HTTPException(status_code=403, detail="无权访问此文件")
            
        if not full_path.exists():
            raise HTTPException(status_code=404, detail="文件不存在")
            
        # 删除文件
        full_path.unlink()
        
        return {
            "success": True,
            "message": "删除成功"
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/storage", response_model=dict)
async def get_storage_info(openid: str = Header(...)):
    """
    获取用户存储信息
    
    Args:
        openid: 用户openid
        
    Returns:
        存储统计信息
    """
    try:
        if not openid:
            raise HTTPException(status_code=401, detail="未登录")
            
        user_dir = Path(STORAGE_CONFIG["base_dir"]) / openid
        if not user_dir.exists():
            return {
                "success": True,
                "data": {
                    "totalFiles": 0,
                    "totalSize": "0 KB",
                    "standardCount": 0,
                    "hdCount": 0,
                    "transparentCount": 0,
                    "layoutCount": 0
                }
            }
            
        stats = file_manager.get_storage_info(str(user_dir))
        
        return {
            "success": True,
            "data": stats
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))